import axios from 'axios'
import {ElMessage} from 'element-plus'
import store from '@/store/modules/user'

const TOKEN_INVALID = 'Token认证失败，请重新登录'
const NETWORK_ERROR = '网络请求异常，请稍后重试'
// const URL = "http://192.168.0.175:9999/"
// const URL = "http://192.168.0.180:9999/"//田
// const URL = "http://192.168.8.150:9999/"//
//const URL = "http://192.168.0.188:9999/" //前端连
// const URL = "http://192.168.0.180:7777/" //张
// const URL = "http://192.168.8.202:7777/"  
// const URL = "http://localhost:9999/"
// const URL = "http://localhost:9999/" //珞
const URL = "http://192.168.0.164:9999/" //珞

// 创建axios实例
const service = axios.create({
    baseURL: `${URL}gpapdm/`, timeout: 30000
})
// request请求拦截器    
service.interceptors.request.use(req => {
    // console.log(req);
    // const timestamp = parseInt(new Date().getTime() / 1000);;//时间戳  
    // console.log(timestamp);
    const token = store.state.token ?? ''
    // 将时间戳添加到请求参数中
    // req.params = {
    //     ...req.params,
    //     timestamp: timestamp
    // }
    // console.log(req);
    if (token) {
        req.headers['token'] = token
    }
    // if (token) {
    //     req.headers['Authorization'] = encodeURIComponent(`Bearer  ${token}`)
    // }
    return req
}, error => {
    return Promise.reject(error)
})

// respone响应拦截器
service.interceptors.response.use(res => {
    const {data, statusText} = res
    if (res?.status === 200) {
        if (data?.respCode == 403) {
            console.log(res, 'request +++ res')
            store.commit("reset");//清除token 和 svg线
            store.commit("resetLines", []);//清除token 和 svg线
            localStorage.removeItem('vuex')
            const errorToLogin = data?.respData?.loginURL
            localStorage.setItem('loginURL', errorToLogin)
            // router.push("/login")
            top.location.href = errorToLogin
            return
        }
        return data
    } else if (res?.status === 40001) {
        // ElMessage.error(statusText)
        ElMessage.error("请重新登录")
    }
    return Promise.reject(TOKEN_INVALID)
}, error => {
    // debugger
    // if (error.code == "ECONNABORTED") {
    //     store.commit("reset");//清除token 和 svg线
    //     router.push("/login")
    // }
    ElMessage.error(NETWORK_ERROR)
    // return Promise.reject(error || NETWORK_ERROR)
})

export default service
